﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NetCore.Common.Enumeration;
using NetCore.Common.Helper;
using NetCore.IRepository.Order_LayerwinDingmachineEquipment;
using NetCore.IRepository.User;
using NetCore.IServices.Order_LayerwinDingmachineEquipment;
using NetCore.Model.Enity;
using NetCore.Model.VeiwModels;
using NetCore.Repository.suger;
using Quartz;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NetCore.Common.Quartz.Monitor
{
    public class CpuMonitorJob : IJob
    {
        private readonly ILogger<CpuMonitorJob> _logger;
        private readonly IEmailsHelper _emailsHelper;
        private readonly IUserRepository _userRepository;
        private readonly IOrder_layerwindingmachineequipmentService _LayerwinDingmachineEquipmentService;
        private readonly IOrder_layerwindingmachineequipmentRepository _order_LayerwindingmachineequipmentRepository;
        public CpuMonitorJob(ILogger<CpuMonitorJob> logger, IEmailsHelper emailsHelper, IUserRepository userRepository, IOrder_layerwindingmachineequipmentService order_LayerwindingmachineequipmentService, IOrder_layerwindingmachineequipmentRepository order_LayerwindingmachineequipmentRepository)
        {
            _logger = logger;
            _emailsHelper = emailsHelper;
            _userRepository = userRepository;
            _LayerwinDingmachineEquipmentService = order_LayerwindingmachineequipmentService;
            _order_LayerwindingmachineequipmentRepository = order_LayerwindingmachineequipmentRepository;
        }
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                #region 发送邮件

                //int value = 50;
                //if (value != 0)
                //    await Console.Out.WriteLineAsync("当前CPU利用率：" + value + "%");
                //if (value >= 50)
                //{
                //    List<IFormFile> formFiles = new List<IFormFile>();
                //    var testFilePath = "F:/文件/架构图.vsdx";
                //    var testFileBytes = File.ReadAllBytes(testFilePath);
                //    using (var ms = new MemoryStream(testFileBytes))
                //    {
                //        IFormFile fromFile = new FormFile(ms, 0, ms.Length,
                //            Path.GetFileNameWithoutExtension(testFilePath),
                //            Path.GetFileName(testFilePath)
                //        );
                //        formFiles.Add(fromFile);//添加附件

                //        //发送邮件
                //        await _emailsHelper.SendEmails(new Mail() { files = formFiles, isbodyHtml = false, mailBody = "当前当前CPU利用率已超标", mailCcArray = new string[1] { "1512623210@qq.com" }, mailTitle = "系统警告邮件", recipientArry = new string[1] { "15874857649@163.com" } });
                //    }
                //    //打印警告日志
                //    _logger.LogWarning((int)EventIdEnum.EventId.CPUWarning, "当前CPU利用率：" + value + "%");
                //}

                #endregion

                #region 添加早、中、晚班统计数据

                //if (await _LayerwinDingmachineEquipmentService.AddShiftProportionRedis())
                //    await Console.Out.WriteLineAsync("Redis添加早、中、晚班统计数据成功！");

                #endregion

                #region 添加指定月份每天生成数据

                //if (await _LayerwinDingmachineEquipmentService.Month_StatisticsDailyData(new Month_StatisticsDailyDataFrom { year = 2021, month = 9, userid = 0, equipmentid = 0, shiftid = 0 }))
                //    await Console.Out.WriteLineAsync("Redis添加指定月份每天生成数据成功！");

                #endregion

                #region 添加指定年份每月生成数据

                //if (await _LayerwinDingmachineEquipmentService.Year_StatisticsDailyData(new Year_StatisticsDailyDataFrom { year = 2021, userid = 0, equipmentid = 0, shiftid = 0 }))
                //    await Console.Out.WriteLineAsync("Redis添加指定年份每月生成数据成功！");

                #endregion

                #region 获取CPU使用率内存占用率

                //获取当前进程对象
                Process cur = Process.GetCurrentProcess();

                PerformanceCounter curpcp = new PerformanceCounter("Process", "Working Set - Private", cur.ProcessName);
                PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", cur.ProcessName);
                PerformanceCounter curtime = new PerformanceCounter("Process", "% Processor Time", cur.ProcessName);

                //上次记录CPU的时间
                TimeSpan prevCpuTime = TimeSpan.Zero;
                //Sleep的时间间隔
                int interval = 1000;

                PerformanceCounter totalcpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");

                SystemInfo sys = new SystemInfo();
                //const int KB_DIV = 1024;
                const int MB_DIV = 1024 * 1024;
                const int GB_DIV = 1024 * 1024 * 1024;
                while (true)
                {
                    //第一种方法计算CPU使用率
                    //当前时间
                    TimeSpan curCpuTime = cur.TotalProcessorTime;
                    //计算
                    double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
                    prevCpuTime = curCpuTime;

                    Console.Out.WriteLine("{0}:{1}  {2:N}KB CPU使用率：{3}", cur.ProcessName, "工作集(进程类)", cur.WorkingSet64 / 1024, value);//这个工作集只是在一开始初始化，后期不变
                    Console.Out.WriteLine("{0}:{1}  {2:N}KB CPU使用率：{3}", cur.ProcessName, "工作集        ", curpc.NextValue() / 1024, value);//这个工作集是动态更新的
                                                                                                                                      //第二种计算CPU使用率的方法
                    Console.Out.WriteLine("{0}:{1}  {2:N}KB CPU使用率：{3}%", cur.ProcessName, "私有工作集    ", curpcp.NextValue() / 1024, curtime.NextValue() / Environment.ProcessorCount);
                    //Thread.Sleep(interval);

                    //第一种方法获取系统CPU使用情况
                    Console.Write("\r系统CPU使用率：{0}%", totalcpu.NextValue());
                    //Thread.Sleep(interval);

                    //第二章方法获取系统CPU和内存使用情况
                    Console.Write("\r系统CPU使用率：{0}%，系统内存使用大小：{1}MB({2}GB)", sys.CpuLoad, (sys.PhysicalMemory - sys.MemoryAvailable) / MB_DIV, (sys.PhysicalMemory - sys.MemoryAvailable) / (double)GB_DIV);
                    Thread.Sleep(interval);
                }

                #endregion
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }
        }
    }
}
